﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace AnimationAdditions
{
	public class PreviewListBox : ListBox
	{
		protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
		{
			if (newValue is IPreviewCollection)
			{
				(newValue as IPreviewCollection).PreviewDelete += OnPreviewDelete;
			}
			if (oldValue is IPreviewCollection)
			{
				(oldValue as IPreviewCollection).PreviewDelete -= OnPreviewDelete;
			}
			base.OnItemsSourceChanged(oldValue, newValue);
		}

		private void OnPreviewDelete(object sender, PreviewDeleteEventArgs e)
		{
			const int animationLengthInMilliseconds = 1000;
			var container = ItemContainerGenerator.ContainerFromItem(e.Item) as UIElement;
			if (container != null)
			{
				Dispatcher.Invoke(new Action(() => 
					container.BeginAnimation(OpacityProperty,
						new DoubleAnimation(0.2,
							new Duration(TimeSpan.FromMilliseconds(animationLengthInMilliseconds))))));
			}
			Thread.Sleep(animationLengthInMilliseconds + (int)(animationLengthInMilliseconds * 0.25));
		}
	}
}
